<?php
/*
Plugin Name: FlickrSet
Plugin URI: http://asdf
Description: Display a flickr set
Author: Fred van den Driessche
Version: 0.01
Author URI: http://fred.vandendriessche.co.uk
License: GPL
*/

//needed so Phlickr works for some reason.
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__));
include_once 'Phlickr/Api.php';
include_once 'Phlickr/User.php';
include_once 'Phlickr/Photoset.php';
include_once 'Phlickr/Photo.php';

define('FS_BASE_URL', get_bloginfo('wpurl').'/wp-content/plugins/flickrset/');
define('FS_API_KEY', '745bf5cec0e4c9a5e9d225ce015b2e84');
define('FS_API_SEC', 'ebef9aa89e16f438');

if(!class_exists('fs_admin')){
	class fs_admin{

		private $api;
		private $authorised;
		
		static function menuPage(){
			$options = unserialize(get_option("fs_options"));
			if(empty($options)){ //create some default options
				$options = array(
					"primary" => true
				);
				update_option("fs_options", serialize($options));
			}
			
			$api = NULL;
			
			switch($_POST['action']) {
			 	case 'auth': //attempting authorisation.
					//print $_POST['frob'];
					$api = new Phlickr_Api(FS_API_KEY, FS_API_SEC);
					try{
						$token = $api->setAuthTokenFromFrob($_POST['frob']);
						update_option('fs_token', $token);
						print '<div id="message" class="updated fade"><p><strong>Authorisation successful</strong></p></div>';
					}catch(Phlickr_MethodFailureException $e){
						print '<div id="message" class="updated fade"><p><strong>Authorisation failed: '. $e->getMessage() . '</strong></p></div>';
					}
					break;
				
			 	case 'reset': //clearing authorisation
					update_option('fs_token', '');
					print '<div id="message" class="updated fade"><p><strong>Authorisation reset</strong></p></div>';
					break;
					
			 	case 'clearcache': //clear cache
					file_put_contents(dirname(__FILE__).'/fs_cache', '');
					print '<div id="message" class="updated fade"><p><strong>Cache cleared</strong></p></div>';
					break;
				
				case 'update': //update fs_options.
					$options["primary"] = ($_POST['primary']) ? true : false;
					update_option("fs_options", serialize($options));
					print '<div id="message" class="updated fade"><p><strong>Options updated</strong></p></div>';
					break;
				default:
					break;
			}

			extract($options);
			
			if(is_null($api)){
				$token = get_option('fs_token'); 
				$api = (empty($token)) ? 
						new Phlickr_Api(FS_API_KEY, FS_API_SEC) :
			 			new Phlickr_Api(FS_API_KEY, FS_API_SEC, $token);
			}
			
			print '<div class="wrap"><h2>flickrSet Options</h2>';
			
			if($api->isAuthValid()){
				$user = new Phlickr_User($api, $api->getUserId());
				print '<div id="auth"><p>Authorised as: ' . $user->getName();
				print '</p><form action="" method="post">';
				print '<p><input type="hidden" name="action" value="reset" />';
				print '<input type="submit" value="Reset Authorisation" /></p></form></div>';
				print '<div>';
				if(is_writable(dirname(__FILE__).'/fs_cache')){
					print '<p>Cache is writable</p>';
					print '<form action="" method="post">';
					print '<p><input type="hidden" name="action" value="clearcache" />';
					print '<input type="submit" value="Clear Cache" /></p></form>';
				}else{
					print '<p>Cache is not writable!</p>';
				}
				print '</div>';?>
				<div><h3>Options</h3>
					<form method="post" action="">
					<p>
						<label>
							<input type="checkbox" <?php if($primary) print 'checked="checked"';?>
							name="primary" value="true" />
							 Use Large Primary image
						</label>
					<p>
					<input type="hidden" name="action" value="update" />
					<p class="submit">
						<input type="submit" name="Submit" value="<?php _e('Update Options »') ?>" />
					</p>
				</form></div><?php
				
			}else{
				$frob = $api->requestFrob();
				$url = $api->buildAuthURL('read', $frob);
				print '<div class="auth"><h3>flickrSet is not currently authorised</h3><p>';
				print '<span style="float:right;width:175px">Click \'Authorise flickrSet\'
				 to allow flickrSet to use your flickr account. Then click 
				 \'Confirm Authorisation\' to begin using flickrSet</span>';
				//users need to follow this link to authorise flickrSet.
				print '<a href="' . htmlentities($url) . '" target="_blank">';
				_e('Authorise flickrSet');
				print '</a></p><form action="" method="post">';
				print '<p><input type="hidden" name="action" value="auth" />';
				print '<input type="hidden" name="frob" value="'.$frob.'" />';
				//Clicking confirm posts the frob to be authorised above
				print '<input type="submit" value="Confirm Authorisation" /></p></form></div>';
			}
			
			echo '</div>'; //close wrap div
		}

		//Add the menu to the options page.
		static function addMenu(){
			add_options_page('flickrSet Options', 'flickrSet', 8, 'flickrsetmenu', array('fs_admin','menuPage'));
		}
	}
}

//Hook up the menu.
add_action('admin_menu', array('fs_admin','addMenu'));

if(!class_exists('fs_content')){
	class fs_handler{
		function shortcodeHandler($atts){
			extract(shortcode_atts(array( //extract atts to their variables.
				'set'=>false
			), $atts));
			if($set){ //need a set Id.
				return fs_handler::handleSet($set);
			}else{
				return "You must specify a set ID";
			}
		}
		
		function handleSet($setid){ //creates html for the set
			$time_start = microtime(true);//timing

			//create api, load cache, and an object for the set
			$token = get_option('fs_token');
			$api = new Phlickr_Api(FS_API_KEY, FS_API_SEC, $token);
			if(!$api->isAuthValid()) return "flickrSet is not authorised.";

			//load cached requests
			$cachefile = dirname(__FILE__) . '/fs_cache';
			$api->setCache(Phlickr_Cache::createFrom($cachefile));

			//create the set object
			$set = new Phlickr_Photoset($api, $setid);
			$slug = fs_handler::slug($set);
			
			$r = '<div class="flickrsetwrap"><ul class="flickrset">';
			
			$options = unserialize(get_option("fs_options"));
			if(empty($options)) print "No options";
			
			foreach($set->getPhotoList()->getPhotos() as $photo){
				$r  .='<li class="flickrsetitem">'
					. fs_handler::imageThumb($photo)
					. fs_handler::lightboxLink($photo, $slug)
					.'</li>';
			}
			
		 	// serialize and save the cache file
		 	$api->getCache()->saveAs($cachefile);
 	 	 	$diff = microtime(true) - $time_start;
 	 	 	return $r . '</ul><br style="clear:both"/><!--'.$diff.'s--></div>';
		}
		
		//$photo is a Phlickr_Photo, return Flickr-friendly 75x75 image html
		function imageThumb($photo){
			$photoUrl = $photo->buildUrl();
			$thumbImgUrl = $photo->buildImgUrl(Phlickr_Photo::SIZE_75PX);
			$title = $photo->getTitle();
			return  '<a href="'.$photoUrl.'" title="'.$title.' on flickr">'.
					'<img src="'.$thumbImgUrl.'" alt="'.$title.'"/>'.
					'</a>';
		}
		
		function lightboxLink($photo, $set){
			$img = $photo->buildImgUrl(Phlickr_Photo::SIZE_500PX);
			$title = fs_handler::getLBTitle($photo);
			$r = '<a class="fslb"'.
				'href="'.$img.
				'" rel="lightbox['.$set.
				']" title="'.$title.'" >'
			.'<img src="'.FS_BASE_URL.'magnifier_zoom_in.png"/></a>';
			return $r;
		}
		
		function getLBTitle($photo){
			$exif = $photo->getExif();
			$p = " &#124; ";
			$e = $exif->getExposure();
			$a = $exif->getAperture();
			$f = $exif->getFocalLength();
			$i = $exif->getIsoSpeed();
			return $f.$p." &fnof;".$a.$p.$e."s ".$p." IS0".$i;
		}
		
		//used with lightbox, removes spaces, to lowercase.
		function slug($string){
			return strtolower(str_replace(' ', '', $string->getTitle()));
		}

		function cssLink(){ //inserts a link to the css into the wp head.
			$href = FS_BASE_URL . 'flickrset.css';
			echo "\t".'<link rel="stylesheet" type="text/css" href="'.$href.'" />';
		}
	}
}

add_shortcode('flickrset', array('fs_handler', 'shortcodeHandler'));
add_action('wp_head', array('fs_handler', 'cssLink'));
?>